document.addEventListener('DOMContentLoaded', async () => {
  // 获取刷新按钮
  const refreshBtn = document.getElementById('refreshBtn');
  const refreshIcon = refreshBtn.querySelector('.refresh-icon');

  // 状态管理
  const statusPanel = document.getElementById('statusPanel');
  const statusText = statusPanel.querySelector('.status-text');

  // 初始化时立即加载历史记录
  await loadBugHistory();

  // 更新状态显示
  async function updateStatus() {
    const { accessToken } = await chrome.storage.sync.get('accessToken');
    
    if (!accessToken) {
      statusPanel.className = 'status not-configured';
      statusText.textContent = '未配置 Access Token';
      refreshBtn.disabled = true;
      statusPanel.classList.remove('error');
    } else {
      statusPanel.className = 'status monitoring';
      statusText.textContent = '正在监控通知';
      refreshBtn.disabled = false;
      statusPanel.classList.remove('error');
    }
  }

  // 显示错误状态
  function showErrorStatus(error) {
    statusPanel.className = 'status error';
    statusText.textContent = error;
    refreshBtn.disabled = false;
    refreshBtn.classList.remove('loading');
  }

  // 获取相对时间
  function getTimeAgo(date) {
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    if (diffDays < 30) return `${diffDays}天前`;
    return date.toLocaleDateString();
  }

  // 初始更新状态
  updateStatus();

  // 刷新按钮点击事件
  refreshBtn.addEventListener('click', async () => {
    refreshBtn.classList.add('loading');
    refreshBtn.disabled = true;

    try {
      // 先清除旧数据
      await chrome.storage.sync.remove('bugHistory');
      
      // 发送手动检查请求并等待响应
      const response = await chrome.runtime.sendMessage({ 
        type: 'manualCheck',
        waitForResponse: true  // 添加标记，表示需要等待响应
      });

      // 等待后台处理完成
      let retries = 0;
      const maxRetries = 50;
      
      while (retries < maxRetries) {
        const { bugHistory } = await chrome.storage.sync.get('bugHistory');
        if (bugHistory && Array.isArray(bugHistory)) {
          console.log('获取到新的 issue 列表:', bugHistory);
          // 更新显示
          await loadBugHistory();
          showTooltip('检查完成');
          break;
        }
        
        await new Promise(resolve => setTimeout(resolve, 100));
        retries++;
        
        if (retries === maxRetries) {
          throw new Error('获取数据超时');
        }
      }

    } catch (error) {
      console.error('检查失败:', error);
      showTooltip(error.message || '检查失败，请重试');
    } finally {
      refreshBtn.classList.remove('loading');
      refreshBtn.disabled = false;
    }
  });

  // 获取当前配置
  const { interval, accessToken, selectedEnterprise } = await chrome.storage.sync.get({ 
    interval: 5,
    accessToken: '',
    selectedEnterprise: ''
  });
  document.getElementById('interval').value = interval;
  document.getElementById('accessToken').value = accessToken;

  // 输入验证和实时反馈
  const intervalInput = document.getElementById('interval');
  intervalInput.addEventListener('input', (e) => {
    const value = parseInt(e.target.value);
    if (value < 1 || value > 60) {
      e.target.style.color = '#ff4444';
    } else {
      e.target.style.color = '#fff';
    }
  });

  // 保存配置
  const saveBtn = document.getElementById('saveConfig');
  const historyLimitInput = document.getElementById('historyLimit');
  const openInNewTabCheckbox = document.getElementById('openInNewTab');

  saveBtn.addEventListener('click', async () => {
    const newInterval = parseInt(intervalInput.value);
    const accessToken = document.getElementById('accessToken').value;
    const enterprise = document.getElementById('enterprise').value;
    const historyLimit = Math.min(10, Math.max(1, parseInt(historyLimitInput.value)));
    historyLimitInput.value = historyLimit; // 确保显示正确的值

    if (newInterval < 1 || newInterval > 60) {
      showTooltip('请输入1-60之间的数字');
      return;
    }

    if (!accessToken) {
      showTooltip('请输入 Access Token');
      return;
    }

    if (!enterprise) {
      showTooltip('请选择企业空间');
      return;
    }

    // 添加保存动画
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;

    try {
      // 检查 token 是否变更
      const { accessToken: oldToken } = await chrome.storage.sync.get('accessToken');
      const tokenChanged = oldToken !== accessToken;
      
      // 保存所有设置
      await chrome.storage.sync.set({ 
        interval: newInterval,
        accessToken: accessToken,
        selectedEnterprise: enterprise,
        historyLimit: historyLimit,
        openInNewTab: openInNewTabCheckbox.checked
      });
      
      // 更新检查频率
      await chrome.runtime.sendMessage({ 
        type: 'updateInterval', 
        interval: newInterval 
      });

      // 如果 token 变更，清理缓存并重新检查
      if (tokenChanged) {
        await chrome.storage.sync.remove(['bugHistory']);
        await chrome.storage.local.clear();
        console.log('Token 已变更，清理缓存');
      }

      // 发送检查请求并等待完成
      await chrome.runtime.sendMessage({ type: 'manualCheck' });
      
      // 等待数据更新完成
      await new Promise((resolve, reject) => {
        const checkData = () => {
          chrome.storage.sync.get(['bugHistory'], (data) => {
            if (data.bugHistory) {
              resolve();
            } else {
              if (attempts++ > 50) {
                reject(new Error('更新超时'));
                return;
              }
              setTimeout(checkData, 100);
            }
          });
        };
        let attempts = 0;
        checkData();
      });

      // 显示成功动画
      saveBtn.style.background = 'linear-gradient(45deg, #4CAF50, #45a049)';
      saveBtn.textContent = '已保存';
      
      // 重新加载历史记录以应用新设置
      loadBugHistory();
      
      // 3秒后恢复按钮样式
      setTimeout(() => {
        saveBtn.style.background = '';
        saveBtn.textContent = '保存设置';
        saveBtn.disabled = false;
      }, 3000);
      
      // 关闭设置抽屉
      settingsDrawer.classList.remove('open');

      // 更新状态显示
      updateStatus();
    } catch (error) {
      console.error('保存设置失败:', error);
      showTooltip('保存失败，请重试');
      saveBtn.textContent = '保存设置';
      saveBtn.disabled = false;
    }
  });

  // 获取配置
  const { 
    historyLimit = 10,
    openInNewTab = true  // 默认在新标签页打开
  } = await chrome.storage.sync.get(['historyLimit', 'openInNewTab']);

  historyLimitInput.value = historyLimit;
  openInNewTabCheckbox.checked = openInNewTab;

  // 加载并显示历史记录
  async function loadBugHistory() {
    const bugList = document.getElementById('bugList');
    
    try {
      const { 
        bugHistory = [], 
        historyLimit = 10
      } = await chrome.storage.sync.get(['bugHistory', 'historyLimit']);
      
      console.log('加载历史记录:', {
        bugHistory,
        totalCount: bugHistory.length,
        displayLimit: historyLimit,
        firstItem: bugHistory[0]
      });

      // 显示历史记录
      if (!bugHistory || bugHistory.length === 0) {
        console.log('无历史记录');
        bugList.innerHTML = '<div class="no-bugs">暂无历史记录</div>';
        return;
      }

      // 生成 HTML 之前记录数据
      const displayItems = bugHistory.slice(0, historyLimit);
      console.log('将要显示的条目:', displayItems);

      bugList.innerHTML = displayItems
        .map(bug => `
          <div class="bug-item" data-url="${bug.html_url}">
            <div class="bug-header">
              <div class="bug-title">${bug.title}</div>
              <div class="bug-state ${bug.issue_state?.toLowerCase()}">${bug.issue_state || 'OPEN'}</div>
            </div>
            <div class="bug-meta">
              <span class="bug-time">${new Date(bug.created_at).toLocaleString()}</span>
              <span class="bug-number">#${bug.number}</span>
            </div>
          </div>
        `)
        .join('');

      // 为每个 bug 项添加点击事件
      attachBugItemClickHandlers();
    } catch (error) {
      console.error('加载历史记录失败:', error);
      bugList.innerHTML = '<div class="no-bugs">加载失败</div>';
    }
  }

  // 为 bug 项添加点击事件处理
  function attachBugItemClickHandlers() {
    document.querySelectorAll('.bug-item').forEach(item => {
      item.addEventListener('click', async () => {
        const url = item.getAttribute('data-url');
        if (!url) {
          console.error('未找到 URL');
          return;
        }

        try {
          // 获取当前的 bugHistory
          const { bugHistory = [] } = await chrome.storage.sync.get('bugHistory');
          
          // 找到并移除被点击的 issue
          const clickedNumber = item.querySelector('.bug-number')?.textContent.replace('#', '');
          const updatedHistory = bugHistory.filter(bug => String(bug.number) !== clickedNumber);
          
          // 保存更新后的历史记录
          await chrome.storage.sync.set({ bugHistory: updatedHistory });
          
          // 从 DOM 中移除该元素（添加淡出动画）
          item.style.transition = 'opacity 0.3s ease-out';
          item.style.opacity = '0';
          
          setTimeout(() => {
            item.remove();
            
            // 如果列表为空，显示"暂无历史记录"
            const bugList = document.getElementById('bugList');
            if (!bugList.children.length) {
              bugList.innerHTML = '<div class="no-bugs">暂无历史记录</div>';
            }
          }, 300);

          // 打开链接
          const { openInNewTab } = await chrome.storage.sync.get({ openInNewTab: true });
          if (openInNewTab) {
            chrome.tabs.create({ url });
          } else {
            chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
              chrome.tabs.update(tabs[0].id, { url });
            });
          }
          
          window.close();
        } catch (error) {
          console.error('处理点击事件时出错:', error);
        }
      });
    });
  }

  // 监听企业选择变化
  document.getElementById('enterprise').addEventListener('change', async () => {
    await chrome.storage.sync.set({ 
      selectedEnterprise: document.getElementById('enterprise').value 
    });
  });

  // 监听 Token 变化时重新加载企业列表
  document.getElementById('accessToken').addEventListener('blur', async () => {
    const accessToken = document.getElementById('accessToken').value;
    
    // 如果 token 为空，不执行操作
    if (!accessToken) {
      return;
    }

    // 清理缓存
    await chrome.storage.sync.remove(['bugHistory', 'selectedEnterprise']);
    await chrome.storage.local.clear();
    console.log('Token 已变更，清理缓存');
    
    // 重新加载企业列表，使用当前输入的 token
    loadEnterprises(accessToken);
  });

  // 初始加载企业列表
  loadEnterprises();

  // 设置抽屉控制
  const settingsDrawer = document.getElementById('settingsDrawer');
  const settingsToggle = document.getElementById('settingsToggle');
  const closeSettings = document.getElementById('closeSettings');
  
  settingsToggle.addEventListener('click', (e) => {
    e.stopPropagation();
    settingsDrawer.classList.toggle('open');
  });
  
  // 关闭按钮点击事件
  closeSettings.addEventListener('click', (e) => {
    e.stopPropagation();
    settingsDrawer.classList.remove('open');
  });

  // 点击抽屉外部关闭抽屉
  document.body.addEventListener('click', (e) => {
    // 如果抽屉未打开，不处理点击事件
    if (!settingsDrawer.classList.contains('open')) {
      return;
    }
    
    if (!settingsDrawer.contains(e.target) && 
        !settingsToggle.contains(e.target) && 
        settingsDrawer.classList.contains('open')) {
      settingsDrawer.classList.remove('open');
    }
  });

  // 阻止抽屉内部点击事件冒泡
  settingsDrawer.addEventListener('click', (e) => {
    e.stopPropagation();
  });

  // 在配置变化时更新状态
  chrome.storage.onChanged.addListener((changes) => {
    if (changes.accessToken || changes.lastSuccessfulFetch) {
      updateStatus();
    }
  });

  // 加载企业列表函数
  async function loadEnterprises(inputToken = null) {
    // 先使用传入的 token，否则从存储中获取
    let accessToken = inputToken;
    if (!accessToken) {
      const stored = await chrome.storage.sync.get('accessToken');
      accessToken = stored.accessToken;
    }
    
    if (!accessToken) {
      document.getElementById('enterprise').innerHTML = '';
      document.getElementById('enterprise').disabled = true;
      document.getElementById('enterprise').setAttribute('placeholder', '请先配置 Access Token');
      return;
    }
    
    try {
      // 使用正确的 API 获取企业列表
      const response = await fetch(`https://gitee.com/api/v5/user/enterprises?access_token=${accessToken}`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json;charset=UTF-8'
        }
      });
      
      if (!response.ok) {
        console.error('获取企业列表失败:', {
          status: response.status,
          statusText: response.statusText
        });
        const errorText = await response.text();
        console.error('错误详情:', errorText);
        throw new Error('获取企业列表失败');
      }
      
      const enterprises = await response.json();
      console.log('获取到的企业列表:', enterprises);
      
      const { selectedEnterprise } = await chrome.storage.sync.get('selectedEnterprise');
      
      document.getElementById('enterprise').innerHTML = `
        ${enterprises.map(ent => `
          <option value="${ent.path}" 
            ${ent.path === selectedEnterprise ? 'selected' : ''}>
            ${ent.name}
          </option>
        `).join('')}
      `;
      
      // 如果没有选中的企业，自动选择第一个
      const select = document.getElementById('enterprise');
      if (!select.value && enterprises.length > 0) {
        select.value = enterprises[0].path;
        // 触发 change 事件以保存选择
        select.dispatchEvent(new Event('change'));
      }
      
      document.getElementById('enterprise').disabled = false;
    } catch (error) {
      console.error('加载企业列表失败:', error);
      document.getElementById('enterprise').innerHTML = '';
      document.getElementById('enterprise').disabled = true;
      document.getElementById('enterprise').setAttribute('placeholder', '加载企业列表失败');
      showTooltip('加载企业列表失败，请检查 Token 权限');
    }
  }

  // 监听来自 background 的消息
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'checkError') {
      showErrorStatus(message.error);
    }
  });

  // 添加消息监听器
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'refreshBugList') {
      // 更新最后获取时间
      const lastUpdateTimeElement = document.getElementById('lastUpdateTime');
      if (lastUpdateTimeElement) {
        lastUpdateTimeElement.textContent = message.lastUpdateTime;
      }
      // 重新加载bug列表
      loadBugHistory();
    }
  });

  // 初始化最后更新时间
  const { lastUpdateTime } = await chrome.storage.sync.get('lastUpdateTime');
  const lastUpdateTimeElement = document.getElementById('lastUpdateTime');
  if (lastUpdateTimeElement && lastUpdateTime) {
    lastUpdateTimeElement.textContent = lastUpdateTime;
  } else if (lastUpdateTimeElement) {
    lastUpdateTimeElement.textContent = '暂无';
  }
});

// 显示提示气泡
function showTooltip(message) {
  // 移除已有的提示
  const existingTooltip = document.querySelector('.tooltip');
  if (existingTooltip) {
    existingTooltip.remove();
  }

  // 创建新提示
  const tooltip = document.createElement('div');
  tooltip.className = 'tooltip';
  tooltip.textContent = message;
  
  // 定位提示
  document.body.appendChild(tooltip);
  const saveBtn = document.getElementById('saveConfig');
  const rect = saveBtn.getBoundingClientRect();
  
  tooltip.style.left = `${rect.left + (rect.width - tooltip.offsetWidth) / 2}px`;
  tooltip.style.top = `${rect.bottom + 8}px`;
  tooltip.style.display = 'block';

  // 3秒后移除提示
  setTimeout(() => {
    tooltip.remove();
  }, 3000);
} 